<template>
  <div>
    <!-- 加载中状态 -->
    <SkeletonLoader 
      v-if="loading && roles.length === 0" 
      type="explore-card" 
      :count="8" 
    />
    
    <!-- 角色列表 -->
    <div v-else-if="roles.length > 0" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
      <RoleCard v-for="r in roles" :key="r.id" v-bind="r" />
    </div>
    
    <!-- 空状态 -->
    <div v-else class="text-center py-12">
      <div class="w-16 h-16 mx-auto mb-4 text-gray-300">
        <svg fill="currentColor" viewBox="0 0 24 24">
          <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
        </svg>
      </div>
      <p class="text-gray-500">暂无角色数据</p>
      <button 
        @click="() => fetchRoles(true)" 
        class="mt-4 px-4 py-2 bg-[#635BFF] text-white rounded-lg hover:bg-[#5a4fcf] transition-colors"
      >
        重新加载
      </button>
    </div>
    
    <!-- 加载更多按钮 -->
    <div v-if="hasMore && roles.length > 0" class="mt-8 text-center">
      <button 
        @click="loadMore"
        :disabled="isLoadingMore"
        class="px-6 py-3 bg-[#635BFF] text-white rounded-lg hover:bg-[#5a4fcf] disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
      >
        <span v-if="!isLoadingMore">加载更多</span>
        <span v-else class="flex items-center gap-2">
          <div class="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
          加载中...
        </span>
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import RoleCard from './RoleCard.vue'
import SkeletonLoader from '@/components/SkeletonLoader.vue'
import { characterInfo } from '@/api'
import type { RoleInfo } from '@/api/interface'
// import { useCacheStore } from '@/stores/modules/cache'

const props = defineProps<{
  category?: string
  keyword?: string
}>()

const roles = ref<RoleInfo[]>([])
const loading = ref(false)
const searchKeyword = ref('')

// 分页状态管理
const currentPage = ref(1)
const totalPages = ref(0)
const hasMore = ref(true)
const isLoadingMore = ref(false)



// 获取角色列表（首次加载或重新搜索）
const fetchRoles = async (reset = true) => {
  if (loading.value) return
  
  loading.value = true
  if (reset) {
    currentPage.value = 1
    roles.value = []
  }
  
  try {
    const params: any = {
      pageNum: currentPage.value,
      pageSize: 20
    }
    
    // 如果有分类参数，添加到请求中
    if (props.category && props.category !== 'all') {
      params.category = props.category
    }
    
    // 如果有搜索关键词，添加到请求中（优先使用props中的keyword）
    const keyword = props.keyword || searchKeyword.value
    if (keyword && keyword.trim()) {
      params.keyword = keyword.trim()
    }
    
    const response = await characterInfo.list(params)
    
    if (response.code === 0 && response.data?.list) {
      if (reset) {
        roles.value = response.data.list
      } else {
        // 追加数据
        roles.value.push(...response.data.list)
      }
      
      // 更新分页信息
      totalPages.value = response.data.pages
      hasMore.value = response.data.hasNextPage
    } else {
      if (reset) {
        roles.value = []
      }
      hasMore.value = false
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    if (reset) {
      // 失败时使用默认数据
      roles.value = [
        { 
          id: 1, 
          name: '智能助手小艾', 
          intro: '专业的工作助手，帮你提升效率，邮件处理和日程管理都不在话下。', 
          image: 'https://picsum.photos/seed/e1/128/128', 
          voice: 'en_female_001',
          isFavorited: 0,
          prompt: '你是一个专业的工作助手',
          category: '工作助手',
          viewCount: 1200,
          isDel: 0,
          createTime: null,
          updateTime: null,
          tags: '助手,效率,文案'
        },
        { 
          id: 2, 
          name: '创作导师莉莉', 
          intro: '高能的内容伴侣与导师，帮你梳理并交付创意，激发灵感。', 
          image: 'https://picsum.photos/seed/e2/128/128', 
          voice: 'en_female_002',
          isFavorited: 0,
          prompt: '你是一个创作导师',
          category: '创意写作',
          viewCount: 856,
          isDel: 0,
          createTime: null,
          updateTime: null,
          tags: '创作,写作,灵感'
        }
      ]
    }
  } finally {
    loading.value = false
  }
}

// 加载更多数据
const loadMore = async () => {
  if (isLoadingMore.value || !hasMore.value) return
  
  isLoadingMore.value = true
  currentPage.value += 1
  
  try {
    await fetchRoles(false)
  } finally {
    isLoadingMore.value = false
  }
}

// 监听分类和关键词变化
watch([() => props.category, () => props.keyword], () => {
  fetchRoles()
}, { immediate: true })

// 监听搜索事件
onMounted(() => {
  // 监听搜索更新事件
  window.addEventListener('search-updated', (event: any) => {
    searchKeyword.value = event.detail.keyword
    fetchRoles()
  })
  
  // 从URL参数中获取搜索关键词
  const urlParams = new URLSearchParams(window.location.search)
  const keyword = urlParams.get('keyword')
  if (keyword) {
    searchKeyword.value = keyword
  }
})

// 暴露状态和方法给父组件
defineExpose({
  hasMore,
  isLoadingMore,
  loading,
  loadMore
})
</script>


